package com.zoweunion.mechanic.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserUserinfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserUserinfoShareResponse;
import com.zoweunion.mechanic.config.AlipayConfig;
import com.zoweunion.mechanic.model.WxUserInfo;
import com.zoweunion.mechanic.util.constants.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class ThirdPartyAuthUtil {
    private static final AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
            AlipayConfig.app_id, AlipayConfig.merchant_private_key,"json", "GBK", AlipayConfig.alipay_public_key, "RSA2");

    /**
     * 获取微信access_token信息
     * @param authCode
     * @return
     */
    public static Map<String, Object> getAccessTokenWX(String authCode) throws MyException {
        String tokenInfoJson;
        try {
            String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    AlipayConfig.wechatAppid, AlipayConfig.appSecret, authCode);
            tokenInfoJson = ThirdPartyAuthUtil.requestGetWX(url);
        } catch (Exception e) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "获取微信token失败");
        }

        return JSONObject.parseObject(tokenInfoJson, Map.class);
    }

    /**
     * 获取微信用户信息信息
     * @param accessToken
     * @param openid
     * @return
     */
    public static WxUserInfo getUserInfoWX(String accessToken, String openid) throws MyException {
        String wxUserInfoJson;
        try {
            String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&&openid=%s", accessToken, openid);
            wxUserInfoJson = ThirdPartyAuthUtil.requestGetWX(url);
        } catch (Exception e) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "获取微信用户信息失败");
        }
        return JSONObject.parseObject(wxUserInfoJson, WxUserInfo.class);
    }

    /**
     * get请求微信接口
     * @param url
     * @return
     */
    private static String requestGetWX(String url) {
        RestTemplate restTemplate = SpringUtils.getBean("restTemplate");
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * 获取阿里token信息
     * @param authCode
     * @return
     * @throws AlipayApiException
     */
    public static AlipaySystemOauthTokenResponse getAccessTokenAlipay(String authCode) throws AlipayApiException {
        // 通过app获取的auth_code 来获取accesstoken, 创建API对应的request类
        AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest();
        tokenRequest.setGrantType("authorization_code");
        tokenRequest.setCode(authCode);
        //通过alipayClient调用API，获得对应的response类
        return alipayClient.execute(tokenRequest);
    }

    /**
     * 获取阿里用户信息
     * @param accessToken
     * @return
     * @throws AlipayApiException
     */
    public static AlipayUserUserinfoShareResponse getUserInfoAlipay(String accessToken) throws AlipayApiException {
        //创建API对应的request类
        AlipayUserUserinfoShareRequest userinfoRequest = new AlipayUserUserinfoShareRequest();
        //在请求方法中传入上一步获得的access_token
        return alipayClient.execute(userinfoRequest, accessToken);
    }

    public static WxUserInfo alipayUserInfoToWxUserInfo(AlipayUserUserinfoShareResponse userInfoAlipay){
        WxUserInfo wxUserInfo = new WxUserInfo();
        wxUserInfo.setId(UuidUtil.get32UUID());
        wxUserInfo.setOpenid(userInfoAlipay.getUserId());
        if (StringUtils.isNotBlank(userInfoAlipay.getNickName())) {
            wxUserInfo.setNickname(userInfoAlipay.getNickName());
        }
        if (StringUtils.isNotBlank(userInfoAlipay.getProvince())) {
            wxUserInfo.setProvince(userInfoAlipay.getProvince());
        }
        if (StringUtils.isNotBlank(userInfoAlipay.getCity())) {
            wxUserInfo.setCity(userInfoAlipay.getCity());
        }
        wxUserInfo.setHeadimgurl(userInfoAlipay.getAvatar());
        if ("m".equals(userInfoAlipay.getGender())) {
            wxUserInfo.setSex(WxUserInfo.SEX_MAN);
        } else {
            wxUserInfo.setSex(WxUserInfo.SEX_WUMAN);
        }
        return wxUserInfo;
    }
}
